package org.yiming.tools.mqtt.client.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.function.Predicate;

/**
 * @author renwenpeng
 * date  2022/1/17 10:30 上午
 */
@Slf4j
public final class IoUtil {
    private IoUtil() {
    }

    public static String inputStream(InputStream inputStream){
        String[] content = new String[1];
        inputStream(inputStream, s -> {
            content[0] = s;
            return false;
        }, true);
        return content[0];
    }

    public static void inputStream(InputStream inputStream, Predicate<String> consumer){
        inputStream(inputStream, consumer, false);
    }
    public static void inputStream(InputStream inputStream, Predicate<String> consumer, boolean once){
        try (InputStream inputStreamTemp = inputStream;
             ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()){
            byte[] bb = new byte[1024];
            int read;
            while ((read = inputStreamTemp.read(bb)) != -1){
                if (!once) {
                    byteArrayOutputStream.reset();
                }
                byteArrayOutputStream.write(bb, 0, read);
                if (!once && Boolean.FALSE.equals(consumer.test(byteArrayOutputStream.toString()))) {
                    return;
                }
            }
            if (once) {
                consumer.test(byteArrayOutputStream.toString());
                return;
            }
        } catch (IOException e) {
            log.info("read byte to string", e);
        }
        consumer.test(null);
    }
}
